package com.wuzhiming.istudy.service.impl;

import com.wuzhiming.istudy.mapper.CourseMapper;
import com.wuzhiming.istudy.pojo.Course;
import com.wuzhiming.istudy.service.BaseService;
import com.wuzhiming.istudy.service.CourseService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: CourseServiceImpl
 * @Description:
 * @Author:zhimingw
 * @Version 1.0
 * @since 2022/3/5 15:43
 */
@Service("courseService")
public class CourseServiceImpl extends BaseService implements CourseService {
    /**
    * @Description: 通过课程类别id查询该类别下所有课程
    * @Param: [id]
    * @return: java.util.List<com.wuzhiming.istudy.pojo.Course>
    * @Author: zhimingw
    * @Date: 2022/3/5
    */
    @Override
    public List<Course> queryAllByTypeId(Integer courseTypeId) {
        List<Course> courses = courseMapper.queryAllByTypeId(courseTypeId);
        return courses;
    }

    /**
    * @Description: 通过课程id查询课程详情
    * @Param: [id]
    * @return: com.wuzhiming.istudy.pojo.Course
    * @Author: zhimingw
    * @Date: 2022/3/6
    */
    @Override
    public Course queryById(Integer id) {
        Course course = courseMapper.queryById(id);
        return course;
    }

    /**
     * @Description: 根据条件获取课程数量
     * @Param: [status]
     * @return: java.lang.Integer
     * @Author: zhimingw
     * @Date: 2021/5/31
     */
    @Override
    public Integer totalCount(Integer status) {
        return courseMapper.totalCount(status);
    }

    @Override
    public List<Course> queryByStatus(Integer status) {
        return courseMapper.queryByStatus(status);
    }

    @Override
    public boolean update(Integer id,String title,String introduce,String courseUrl,Integer courseSections,String courseTime,Integer courseTypeId,Integer courseStageId,Integer status,Integer sort) {
        // 首先获取课程
        Course course = courseMapper.queryById(id);
        course.setTitle(title);
        course.setIntroduce(introduce);
        course.setCourseUrl(courseUrl);
        course.setCourseSections(courseSections);
        course.setStatus(status);
        course.setCourseTime(courseTime);
        course.setCourseTypeId(courseTypeId);
        course.setCourseStageId(courseStageId);
        course.setRecentEdit(new Date());
        course.setSort(sort);
        //如果原来的发布时间为空
        if(ObjectUtils.isEmpty(course.getPublishTime())){
            course.setPublishTime(new Date());
        }
        //更新文章
        if(courseMapper.update(course)==1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean update(Course course) {
        if(courseMapper.update(course)==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteById(Integer id) {
        if(courseMapper.deleteById(id)==1){
            return true;
        }
        return false;
    }

    @Override
    public Integer deleteTrash() {
        return courseMapper.deleteTrash();
    }

    @Override
    public Integer publish(String title, String introduce, String courseUrl, Integer courseSections, String courseTime, Integer courseTypeId, Integer courseStageId,Integer status,Integer sort) {
        Course course = new Course();
        course.setTitle(title);
        course.setIntroduce(introduce);
        course.setStatus(status);
        course.setCourseUrl(courseUrl);
        course.setCourseSections(courseSections);
        course.setCourseTime(courseTime);
        course.setCourseTypeId(courseTypeId);
        course.setCourseStageId(courseStageId);
        course.setSort(sort);
        if (status != 0) {
            course.setPublishTime(new Date());
        }
        course.setRecentEdit(new Date());
        course.setReadCount(0);
        if(courseMapper.insert(course)==1){
            // 处理输入的标签集合和文集
            return course.getId();
        }else{
            return 0;
        }
    }

    @Override
    public List<Course> getHotCourse() {
        return courseMapper.getHotCourse();
    }

    @Override
    public List<Course> getCourseByStageId(Integer courseStageId) {
        return courseMapper.getCourseByStageId(courseStageId);
    }

    @Override
    public long getEsDocCount() {
        // 创建搜索请求
        SearchRequest searchRequest = new SearchRequest("iStudy");
        // 创建搜索对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 设置查询条件
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());

        searchRequest.source(searchSourceBuilder);

        // 执行搜索
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.getHits().getTotalHits().value;
    }

    @Override
    public void initEs() {
        courseRespository.deleteAll();
        List<Course> courses = courseMapper.queryByStatus(1);
        for(Course course:courses){
            course.setStatus(null);
            course.setCourseTypeId(null);
            course.setCourseStageId(null);
            course.setRecentEdit(null);
            courseRespository.save(course);
        }
    }

    @Override
    public List<Course> searchFromEs(String content) {
        List<Course> result = new ArrayList<>();
        //创建搜索请求
        SearchRequest searchRequest = new SearchRequest("iStudy");
        //创建搜索对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置查询条件
        searchSourceBuilder.query(QueryBuilders.multiMatchQuery(content,"title","introduce"))
                .from(0)
                .size((int)getEsDocCount())
                .highlighter(new HighlightBuilder().field("*").requireFieldMatch(false).preTags("<span style='color:red;font-weight:500'>").postTags("</span>"));
        searchRequest.source(searchSourceBuilder);
        //执行搜索
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHit[] hits = response.getHits().getHits();
        for(SearchHit hit:hits){
            Map<String, Object> map = hit.getSourceAsMap();
            Course temp = new Course();
            temp.setId((Integer)map.get("id"));
            temp.setImgUrl(map.get("imgUrl").toString());
            temp.setTitle(map.get("title").toString());
            temp.setIntroduce(map.get("introduce").toString());
            temp.setReadCount((Integer) map.get("readCount"));
            Map<String, HighlightField> fields = hit.getHighlightFields();
            //设置标题高亮
            if(fields.containsKey("title")){
                temp.setTitle(fields.get("title").fragments()[0].toString());
            }
            // 设置摘要高亮
            if (fields.containsKey("introduce")) {
                temp.setIntroduce(fields.get("introduce").fragments()[0].toString());
            }
            result.add(temp);
        }
        return result;
    }
}
